//*********************************************************************
// Copyright (C) 2014 Hell Prototypes / www.hellprototypes.com
// 
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or (at
// your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
//********************************************************************
#include <avr/io.h>
#include <avr/power.h>
#include <util/delay.h>
#include "common.h"

#define START_BAT_ADC()		setbit(ADCA.CH0.CTRL, 7)
#define WAIT_BAT_CONVERT()	do{ while(!testbit(ADCA.CH0.INTFLAGS,0)); ADCA.CH0.INTFLAGS = 1;}while(0)

void battery_init()
{
	ADCA.CH0.MUXCTRL  = 0x00;	// Channel 0 input: ADC0 pin
	ADCA.CH0.CTRL	  = 0x01;	// Single-ended positive input signal

	PORTA.PIN0CTRL	  = 0x07;  //Digital input buffer disabled
}

// Get voltage
uint battery_voltage()
{
    uint voltage;

	byte old_ref = ADCA.REFCTRL;

	ADCA.REFCTRL	  = 0x02;	// REF= 1V

	//delay_us(10);
	ms_delay(3);
	START_BAT_ADC();
	WAIT_BAT_CONVERT();
    voltage = ((ulong)ADCA.CH0.RESL * 4900) / 256 - 245;//0.05*4900 = 245

	ADCA.REFCTRL = old_ref;

    return voltage;
}
